<template>
  <div id="drawContainer" class="drawContainer">
    <div id="map" class="mapContent" />
    <!-- 问题类型弹窗 -->
    <div v-show="problemPopupShow" ref="problemPopupDOM" class="problemInfo">
      <div class="item">
        <div class="title">问题类型:&nbsp;</div>
        <div class="value">{{ problemInfo.typeName }}</div>
      </div>
      <div class="item">
        <div class="title">经纬度:&nbsp;</div>
        <div class="value">{{ problemInfo.lnglat[0] }},{{ problemInfo.lnglat[1] }}</div>
      </div>

      <div class="item" style="margin-bottom:10px">
        <div class="title">问题图片:&nbsp;</div>
        <img
          v-for="(item, index) in problemInfo.imgList"
          :key="index"
          :src="item.src"
          @click="showImage(item.src)"
        >

      </div>

    </div>

    <!-- 遮罩层 -->

    <div v-if="mockShow" class="mock" @click="mockShow=!mockShow">
      <img v-show="picturePreviewShow" :src="previewPictureSrc">
    </div>

  </div>
</template>
<script>
import mapboxgl from 'mapbox-gl'
import 'mapbox-gl/dist/mapbox-gl.css'
import { onMounted, reactive, toRefs, ref, unref, createApp } from 'vue'
import { getTaskInspectionType } from '@/api/task/index'
import { ChangeQuestionType } from '@/api/question/index.js'
import imagesMap from '@/components/BaseMap/tools/gisImage.js'

// 问题类型列表

export default {
  props: {
    detail: {
      type: Object,
      required: true
    }
  },
  setup(props, { emit }) {
    const data = reactive({
      problemPopupShow: false,
      map: null,
      problemInfo: {
        typeName: '',
        lnglat: '',
        imgList: []
      },
      previewPictureSrc: '',
      picturePreviewShow: false,

      questionTypeSelected: null, // 所选择的问题类型,
      typeList: [],
      problemId: '',
      mockShow: false,
      problemPopup: null,
      problemPopupDOM: null
    })
    // 初始化地图
    const initMap = () => {
      mapboxgl.accessToken =
        'pk.eyJ1IjoiNDMyMzQyMjIyMiIsImEiOiJjbDhtcW5qcGkwNWVnM3ZwYnYyNWV2MDJ6In0.Rd7TsRZfKQtke3KT1JduXQ'
      data.map = new mapboxgl.Map({
        container: 'map',
        style: {
          // 设置版本号，一定要设置
          version: 8,

          // 添加来源
          sources: {
            tdtVec: {
              type: 'raster',
              tiles: [
                'https://t0.tianditu.gov.cn/vec_w/wmts?tk=f634525a82da65f715d168d7ba1899c0&SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&FORMAT=tiles'
              ],
              tileSize: 256,
              maxZoom: 17
            }
          },
          layers: [
            {
              // 图层id，要保证唯一性
              id: 'tdtVec',
              // 图层类型
              type: 'raster',
              // 数据源
              source: 'tdtVec',
              // 图层最小缩放级数
              minZoom: 0,
              // 图层最大缩放级数
              maxZoom: 17
            }
          ],
          glyphs: 'mapbox://fonts/mapbox/{fontstack}/{range}.pbf',
          sprite: 'mapbox://sprites/mapbox/bright-v8'
        },
        center: [118.76, 32.06],
        zoom: 7,
        maxZoom: 17,
        maxPitch: 0,
        dragRotate: false,
        renderWorldCopies: false
      })
      // 获取问题点的经纬度并跳转到问题点

      const positionArr = props.detail.lnglat.split(',')

      const position = [parseFloat(positionArr[0]), parseFloat(positionArr[1])]

      // // 获取问题点地理位置
      const problemGeoJson = {
        type: 'FeatureCollection',
        features: [
          {
            type: 'Feature',
            properties: props.detail,
            geometry: {
              type: 'Point',
              coordinates: position
            }
          }
        ]
      }
      // // 添加问题点资源与图层
      data.map.on('load', () => {
        data.map.loadImage(imagesMap['wenti'], (error, image) => {
          if (error) throw error
          data.map.addImage('icon', image)
        })
        data.map.addSource('problemPoint', {
          type: 'geojson',
          data: problemGeoJson
        })
        data.map.addLayer({
          id: 'problemPoint',
          type: 'symbol',
          source: 'problemPoint',
          layout: {
            'icon-image': 'icon',
            'icon-size': 1,

            'icon-rotation-alignment': 'map',
            'icon-allow-overlap': true,
            'icon-ignore-placement': true
          }
        })
        // 地图飞到问题点
        data.map.flyTo({
          center: position,
          zoom: 10
        })
        data.map.on('click', 'problemPoint', flagPointHandle)
      })
    }
    // 单击问题icon显示问题弹窗
    const flagPointHandle = (e) => {
      var features = data.map.queryRenderedFeatures(e.point, {
        layers: ['problemPoint']
      })
      // 获取到经纬度
      const position = [parseFloat(features[0].properties.longitude), parseFloat(features[0].properties.latitude)]

      // console.log(features[0].properties, '点属性信息')
      data.problemInfo = features[0].properties
      data.problemInfo.typeName = features[0].properties.questionName

      data.problemInfo.lnglat = data.problemInfo.lnglat.split(',')

      data.problemInfo.lnglat[0] = parseFloat(data.problemInfo.lnglat[0]).toFixed(6)
      data.problemInfo.lnglat[1] = parseFloat(data.problemInfo.lnglat[1]).toFixed(6)
      const imgStr = features[0].properties.fileImage.split(',')
      data.problemId = features[0].properties.id
      // console.log(imgStr, '图片路径数组')
      data.problemInfo.imgList = []
      imgStr.map((item) => {
        const obj = {}
        obj.src = item
        // console.log(obj, '新加对象')
        data.problemInfo.imgList.push(obj)
      })
      data.problemPopupShow = true
      // 显示弹窗
      data.problemPopup = new mapboxgl.Popup({ closeButton: false })
        .setLngLat(position)
        .setDOMContent(data.problemPopupDOM)
        .setMaxWidth('577px')
        .addTo(data.map)
    }
    const hiddenProblemPopup = () => {
      data.problemPopupShow = false
    }
    // 点击图片出现的弹窗
    const showImage = (url) => {
      data.previewPictureSrc = url
      data.picturePreviewShow = true
      data.mockShow = true
    }
    const hiddenPicturePreview = () => {
      data.picturePreviewShow = false
    }
    // 获取问题类型数据
    const getQusetionType = async function() {
      const { data } = await getTaskInspectionType()

      // console.log(data, '传过来的数据信息')
      getQuestionTypeList(data)
    }
    const getQuestionTypeList = (newArr) => {
      const arr = []
      newArr.map((item) => {
        const obj = {}
        obj.value = item.code
        obj.label = item.content
        arr.push(obj)
      })
      data.typeList = arr
    }
    // 改变问题类型事件
    const handleUpdateProblem = (value) => {}
    // 确认问题类型
    const confirmProblemType = () => {
      ChangeQuestionType(data.problemId + '/' + data.questionTypeSelected)
        .then((res) => {
          if (res.code == 0) {
            // 关闭问题类型弹窗
            data.problemPopupShow = false
          }
        })
        .catch((e) => {
          console.log(e)
        })
    }
    onMounted(() => {
      initMap()
      getQusetionType()
    })
    return {
      ...toRefs(data),
      hiddenProblemPopup,
      showImage,
      hiddenPicturePreview,
      handleUpdateProblem,
      confirmProblemType
    }
  }
}
</script>
<style scoped lang='scss'>
.drawContainer {
  width: 100%;
  height: 100%;
  position: relative;

  .mapContent {
    width: 100%;
    height: 100%;
  }
  //问题类型弹窗
  .problemInfo {

    .item {
    position: relative;
    font-size: 14px;
    color: #fff;

    padding-left: 90px;
    .title {
      position: absolute;
      left: 0px;
      top: 0px;
      width: 80px;
      text-align: right;
    }
    .clusterNumber {
      width: 80px;
    }
    img {
      width: 67px;
      height: 37px;
      margin-right: 10px;
    }
  }
  }
  // 图片预览弹窗
  .picturePreviewPopup {
    position: absolute;
    width: 577px;
    border-radius: 6px;
    left: 870px;
    top: 370px;
    background-color: white;
    .title {
      width: 100%;
      height: 57px;
      border-bottom: 1px solid #e4e7ed;
      position: relative;
      font-size: 20px;
      font-family: Noto Sans SC-Medium, Noto Sans SC;
      font-weight: 500;
      color: #333333;
      padding-left: 29px;
      line-height: 57px;
      img {
        position: absolute;
        width: 24px;
        height: 24px;
        right: 20px;
        top: 50%;
        margin-top: -12px;
      }
    }
    .content {
      box-sizing: border-box;
      display: flex;
      justify-content: center;
      padding: 20px 0;
    }
  }

}
 .mock{
     position:absolute;
 top:0;
bottom:0;
 left:0;
 right:0;
background: rgba(0,0,0,0.3);
display:flex;
justify-content:center;
align-items:center;
}
:deep(.mapboxgl-popup-content) {
  background: #2d2d2d !important;
  font-size: 14px;
  font-family: Noto Sans SC-Regular, Noto Sans SC;
  font-weight: 400;

}
:deep(.mapboxgl-popup-anchor-bottom .mapboxgl-popup-tip) {
  border-top-color: #2d2d2d !important;
}
</style>
